using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
using Game.Networking;
using UnityEngine.UI;

namespace Game.UI {
	public sealed class ChatWindow : UIWindow {
		public int MaxMessageCount = 50;
		public TMP_Text TextField;
		public TMP_InputField InputLine = null;
		public Scrollbar Scrollbar;

		ChatReceiver _impl;

		StringBuilder _sb = new StringBuilder(4096);
		Queue<ChatMessage> _messages;

		protected override void Awake() {
			base.Awake();
			InputLine.onSubmit.AddListener(OnChatSubmit);
			InputLine.onSelect.AddListener(OnInputLineSelected);
			_messages = new Queue<ChatMessage>(MaxMessageCount);
		}

		private void Start() {
			if ( GameManager.Instance.IsClient ) {
				_impl = new ClientChatReceiver();
			} else if ( GameManager.Instance.IsServer) {
				_impl = new ServerChatReceiver();
			}
			if ( _impl != null ) {
				_impl.Init();
				_impl.OnMessageReceived.Subscribe(this, OnMessageReceived);
			}
		}

		protected override void OnDestroy() {
			base.OnDestroy();
			if ( _impl != null ) {
				_impl.DeInit();
				_impl.OnMessageReceived.Unsubscribe(OnMessageReceived);
			}
		}

		void OnMessageReceived(ChatMessage message) {
			_messages.Enqueue(message);
			if ( _messages.Count > MaxMessageCount ) {
				_messages.Dequeue();
			}
			UpdateView();
		}

		void UpdateView() {
			foreach ( var item in _messages ) {
				_sb.AppendLine(item.ToChatString());
			}
			TextField.text = _sb.ToString();
			_sb.Clear();
			Scrollbar.value = 1;
		}

		void OnChatSubmit(string text) {
			if (Input.GetKey(KeyCode.Escape) ) {
				return;
			}
			if ( !string.IsNullOrEmpty(text) ) {
				_impl.SendMessage(text.TrimEnd('\r', '\n'));
			}
			InputLine.text = string.Empty;
			InputLine.ActivateInputField();
		}

		public override void OnWindowShow() {
			base.OnWindowShow();
			InputLine.ActivateInputField();
		}

		void OnInputLineSelected(string _) {
			_owner.HasFocus = true;
		}
	}
}
